package com.product.utils;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.UUID;

@Component
public class JwtUtil {
    // 设置有效期30min
    private static final long JWT_EXPIRE = 30 * 60 * 1000L;
    // 生成密钥
    private static final SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    // 密钥转 Base64 编码
    private static final String base64Key = Encoders.BASE64.encode(secretKey.getEncoded());

    /**
     * 用jwt创建token
     *
     * @param data
     * @return
     */
    public String createToken(Object data) {
        // 当前时间
        long currentTime = System.currentTimeMillis();
        // 过期时间
        long expireTime = currentTime + JWT_EXPIRE;
        // 构建jwt
        JwtBuilder builder = Jwts.builder()
                                 .setId(UUID.randomUUID() + "")
                                 .setSubject(JSON.toJSONString(data))
                                 .setIssuer("system")
                                 .setIssuedAt(new Date(currentTime))
                                 .signWith(secretKey, SignatureAlgorithm.HS256)
                                 .setExpiration(new Date(expireTime));
        return builder.compact();
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public Claims parseToken(String token) {
        Claims body = Jwts.parser()
                          .setSigningKey(base64Key)
                          .build()
                          .parseClaimsJws(token)
                          .getBody();
        return body;
    }

    /**
     * 解析token，返回json格式对象
     *
     * @param token
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> T parseToken(String token, Class<T> tClass) {
        Claims body = Jwts.parser()
                          .setSigningKey(base64Key)
                          .build()
                          .parseClaimsJws(token)
                          .getBody();
        return JSON.parseObject(body.getSubject(), tClass);
    }

}
